package com.weacar.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.weacar.R;
import com.weacar.bean.BaseBean;
import com.weacar.bean.LoginBean;
import com.weacar.config.Constans;
import com.weacar.utils.AppManager;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.SharedPreferenceUtil;
import com.weacar.utils.SystemUtil;
import com.weacar.utils.ToastUtil;
import com.weacar.utils.ToolsUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 登录页面
 */
public class LoginActivity extends BaseActivity {


    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_password)
    EditText et_password;

    @OnClick({R.id.iv_back, R.id.iv_phone_clean, R.id.iv_password_clean, R.id.tv_login, R.id.tv_reg, R.id.tv_forget_password})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_phone_clean:
                et_phone.setText("");
                break;
            case R.id.iv_password_clean:
                et_password.setText("");
                break;
            case R.id.tv_login:
                Login();
                break;
            case R.id.tv_reg:
                startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
                break;
            case R.id.tv_forget_password:
                startActivity(new Intent(getApplicationContext(), ForgetPasswordActivity.class));
                break;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarStyle("1");
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        AppManager.getInstance().addActivity(this);

        LoginBean loginBean = SharedPreferenceUtil.getObject(getApplicationContext(), "loginBean");
        if (loginBean != null) {
            LogUtils.d(loginBean.toString());
        } else {
            LogUtils.d("用户未登录");
        }

    }


    public void Login() {

        if (!ToolsUtil.isPhone(et_phone.getText().toString().trim())) {
            ToastUtil.showShort(getApplicationContext(), "请输入正确的手机号");
            return;
        }

        if (!ToolsUtil.isPassword(et_password.getText().toString().trim())) {
            ToastUtil.showShort(getApplicationContext(), "请输入正确格式的密码");
            return;
        }

        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }


        try {
            showLoading("正在登录中...");
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.login_url);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("username", et_phone.getText().toString().trim());
            js_request.put("password", et_password.getText().toString().trim());
            js_request.put("android_id", SystemUtil.getAndroidId(getApplicationContext()));
            js_request.put("phoneCompany", SystemUtil.getDeviceBrand());
            js_request.put("device", SystemUtil.getSystemModel());
            js_request.put("androidCode", SystemUtil.getSystemVersion());
            js_request.put("versionCode", SystemUtil.getAppVersion(getApplicationContext()));

            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
            LogUtils.d("Login_url =  " + params.getUri());
            LogUtils.d("login_params = " + params.getBodyContent());

            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    closeLoading();
                    LogUtils.d("result = " + result);
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null && baseBean.getCode() == 1) {
                        try {
                            LoginBean loginBean = gson.fromJson(DesUtil.decrypt(baseBean.getData()), LoginBean.class);
                            LogUtils.d(loginBean.toString());
                            if (loginBean != null) {
                                SharedPreferenceUtil.setObject(getApplicationContext(), "loginBean", loginBean);
                                ToastUtil.showShort(getApplicationContext(), "登录成功欢迎回来");
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                                        startActivity(intent);
                                        finish();
                                    }
                                }, 500);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        // 错误信息提示
                        if (baseBean != null) {
                            try {
                                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(DesUtil.decrypt(baseBean.getData()));
                                ToastUtil.showShort(getApplicationContext(), jsonObject.get("msg").toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showShort(getApplicationContext(), "系统异常");
                        }
                    }


                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    closeLoading();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    closeLoading();
                }

                @Override
                public void onFinished() {
                    closeLoading();
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
